const mongoose = require('mongoose');
const User = require('../models/User');
const Challenge = require('../models/Challenge');
require('dotenv').config();

async function initDatabase() {
  try {
    await mongoose.connect(process.env.MONGODB_URI);
    console.log('连接到MongoDB成功');

    // 创建索引
    await User.collection.createIndex({ email: 1 }, { unique: true });
    await User.collection.createIndex({ username: 1 }, { unique: true });
    await Challenge.collection.createIndex({ title: 1 });
    
    console.log('索引创建成功');

    // 创建测试用户
    const testUser = {
      username: 'test',
      email: 'test@example.com',
      password: 'test123456'
    };

    const adminUser = {
      username: 'admin',
      email: 'admin@example.com',
      password: 'admin123456',
      role: 'admin'
    };

    // 如果用户不存在则创建
    await User.findOneAndUpdate(
      { email: testUser.email },
      testUser,
      { upsert: true, new: true }
    );

    await User.findOneAndUpdate(
      { email: adminUser.email },
      adminUser,
      { upsert: true, new: true }
    );

    console.log('测试用户创建成功');

    // 创建示例挑战
    const challenges = [
      {
        title: "零塑料周",
        description: "一周内不使用任何一次性塑料制品",
        points: 100,
        duration: "7天",
        category: "日常生活",
        difficulty: "中等",
        tasks: [
          { text: "自带购物袋", points: 20 },
          { text: "使用可重复使用的水杯", points: 20 },
          { text: "拒绝一次性餐具", points: 30 },
          { text: "选择无包装商品", points: 30 }
        ]
      }
      // ... 其他挑战
    ];

    await Challenge.deleteMany({}); // 清除现有挑战
    await Challenge.insertMany(challenges);
    
    console.log('示例挑战创建成功');
    console.log('数据库初始化完成');

  } catch (error) {
    console.error('数据库初始化失败:', error);
  } finally {
    await mongoose.connection.close();
  }
}

initDatabase(); 